const port = 9527
const path = require('path');

function resolve(dir) {
    return path.join(__dirname, dir)
}
//压缩js代码并支持es6
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
    publicPath: '/jrfk/i',
    //publicPath: '/jrfk/fkfx',
    assetsDir: 'static',
    outputDir: process.env.NODE_ENV === "dev" ? 'devdist' : 'risk_front', // 不同的环境打不同包名
    lintOnSave: false,
    productionSourceMap: false,
    runtimeCompiler:true,
    css: {
        /* css相关配置 */
        extract: true,
        /* 默认值：生产环境下是 true，开发环境下是 false。是否将组件中的 CSS 提取至一个独立的 CSS 文件中 (而不是动态注入到 JavaScript 中的 inline 代码)。*/
        sourceMap: false,
        loaderOptions: {
            // 给 sass-loader 传递选项
            sass: {
                // 根据自己样式文件的位置调整
                prependData: `@import "./src/styles/mixin.scss";`
            }
        },
        requireModuleExtension: true
    },
    devServer: {
        host:'0.0.0.0',
        port: port,
        open: true,
        overlay: {
            warnings: false,
            errors: false
        },
        compress: true,
        disableHostCheck: true, //webpack4.0 开启热更新,
        proxy: {
            [process.env.VUE_APP_BASE_API]: {
                //target: 'https://www.zbifc.com/jrfk',
                //target: 'http://192.168.2.193:9002/jrfk',
                //target: process.env.VUE_APP_BASE_URL,
                target: process.env.VUE_APP_ASSESS_URL,
                changeOrigin: true,
                pathRewrite: {
                    ["^" + process.env.VUE_APP_BASE_API]: ""
                },
                xfwd:true,
                onProxyRes(proxyRes, req) {
                    const realUrl = new URL(req.url || '', process.env.VUE_APP_ASSESS_URL)?.href || '';
                    proxyRes.headers['x-real-url2'] = realUrl
                }
            },
        }
    },

    //webpack 配置
    chainWebpack: (config) => {
        //对images进行处理
        config.module
            .rule('images')
            .test(/\.(png|jpe?g|gif|webp)(\?.*)?$/)
            .use('url-loader')
            .loader('url-loader')
            .tap(options => {
                // 修改它的选项...
                options.fallback.options.name = 'static/img/[name]-risk_dist.[ext]?'
                options.limit = 1024 *
                    10; //当图片的大小小于 1KB ,则会被转为 base64格式，打包进js文件，大于1KB,则会被打包进 img 文件夹，供链接请求获取。
                return options
            });
        config.module
            .rule('svg')
            .exclude.add(resolve('src/icons'))
            .end()
        config.module
            .rule('icons')
            .test(/\.svg$/)
            .include.add(resolve('src/icons'))
            .end()
            .use('svg-sprite-loader')
            .loader('svg-sprite-loader')
            .options({
                symbolId: 'icon-[name]'
            })
            .end()
        // 修复HMR
        config.resolve.symlinks(true);
        // 别名配置 // 开发生产共同配置
        config.resolve.alias
            .set('@', path.resolve('./src'))
            .set('@a', path.resolve('./src/assets'))
            .set('@c', path.resolve('./src/components'))
            .set('@v', path.resolve('./src/view'));
    },
    //webpack 配置
    configureWebpack: config => {
        if (process.env.NODE_ENV === 'prod') {
            config.mode = 'production'
            const plugins = [];
            let optimization = {
                runtimeChunk: 'single',
                splitChunks: {
                    chunks: 'all',
                    maxInitialRequests: Infinity,
                    minSize: 20000,
                    cacheGroups: {
                        vendor: {
                            test: /[\\/]node_modules[\\/]/,
                            name(module) {
                                // get the name. E.g. node_modules/packageName/not/this/part.js
                                // or node_modules/packageName
                                const packageName = module.context.match(
                                    /[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
                                // npm package names are URL-safe, but some servers don't like @ symbols
                                return `npm.${packageName.replace('@', '')}`
                            }
                        }
                    }
                },
                minimize: true,
                minimizer: [
                    new TerserPlugin({
                        sourceMap: true,
                        cache: true, // 是否缓存
                        parallel: true, // 是否并行打包
                        extractComments: false, //允许自定义条件提取注释，指定提取文件名和banner。`${file}.LICENSE`;// https://blog.csdn.net/u013884068/article/details/83511343
                        terserOptions: {
                            warnings: false,
                            compress: {
                                drop_console: false, // 注释console
                                drop_debugger: false, // 注释debugger
                                pure_funcs: ["console.log"]
                            }
                        }
                    })
                ]
            };
            config.plugins = [...config.plugins, ...plugins];
            Object.assign(config, {
                optimization,
                // 给文件添加版本号
                output: {
                    ...config.output,
                    filename: `static/js/[name].[contenthash:5].js`,
                    chunkFilename: `static/js/[name].[contenthash:5].js`
                },
                // 插件配置
                plugins: [
                    ...config.plugins
                ]
            })
        } else {
            config.mode = 'development'
        }
    }
};
